package cn.tedu.micro.demo.amqp;

import cn.tedu.micro.demo.pojo.MessagePO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 希望使用这个对象来发送我当前项目中所有的业务数据到rabbitmq
 */
@Component
@Slf4j
public class AmqpProducer<T> {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发送一个普通消息没有路由key值 默认"" 到一个目标交换机
    public void send(String exchange,T msg){
        this.send(exchange,"",msg);
    }
    //发送一个普通消息有路由key值
    public void send(String exchange,String routingKey,T msg){
        this.send(exchange,routingKey,msg,null);
    }
    //发送一个普通消息 发送消息超时时间毫秒数
    public void send(String exchange,String routingKey,T msg,Long expiration){
        MessageProperties properties=new MessageProperties();
        if (expiration!=null){
            properties.setExpiration(expiration.toString());
        }
        properties.setContentType("application/json;charset=utf-8");
        Message message=new Message(searializer(msg),properties);
        rabbitTemplate.convertAndSend(exchange,routingKey,message);
    }

    public static <T> byte[] searializer(T msg){
        //1. 对象转化成json
        String msgJson = JSON.toJSONString(msg);
        log.info("发送的消息为：{}",msgJson);
        //2. json字符串转化成字节数组
        return msgJson.getBytes();
    }
}
